import { fenceUserTypeHash, repositoryHash } from '.';
import { transferOption } from '@/support/utils';
import {
  Button,
  Card,
  Cascader,
  Checkbox,
  Col,
  DatePicker,
  Form,
  message,
  Radio,
  Row,
  Select,
  Space,
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import { Map } from 'react-amap';
import router from 'umi/router';

const effectTypeOptions = [
  { label: '无限制', value: 0 },
  { label: '限制', value: 1 },
];
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 16 },
  },
};
const FormItem = Form.Item;
const { Option } = Select;
const mapStateToProps = (state: any) => ({
  baseUser: state.baseUser,
  loading: state.loading.effects['electricFenceMng/postObj'],
});
class DistrictAdd extends PureComponent<any, any> {
  insComplete = (() => {
    let t: any;
    const promise = new Promise(resolve => {
      t = resolve;
    });
    promise.resolve = t;
    return promise;
  })();

  ins: any;
  geojson: any;

  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      record: null,
      isAdd: true,
      effectType: 0,
      provinceList: [],
      cityList: [],
      areaList: [],
      orgData: [],
      originData: '',
      dealerData: [],
      orgFilterData: [],
      isDetail: !!props.location.query.isDetail,
      dealerOptions: [],
      fenceUserType: null,
      currentOrgSid: null,
    };
  }

  componentDidMount() {
    this.open();
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/getData',
      payload: {
        url: '/common/area/list',
        level: 'PROVINCE',
      },
      callback: (res: any) => {
        this.setState({ provinceList: res.data });
      },
    });
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/org/findorglistbytoken',
      },
      callback: (res: any) => {
        if (res.statusCode === '0' && res.data && res.data.length) {
          const originData = JSON.stringify(res.data);
          const orgData = JSON.parse(originData);
          this.setState({
            originData,
            orgData: this.dealTreeData(orgData[0].orgParent, orgData),
          });
          // this.getOrgFilterData();
        }
      },
    });
    // dispatch({
    //   type: 'basedata/fetchDealerByLogin',
    //   callback: (response: { data: any[] }) => {
    //     // if (response.statusCode === '0') {
    //     this.setState({
    //       dealerOptions: response.data
    //         ?.filter((item: { code: string }) => item.code !== '')
    //         .map(d => {
    //           //  需求迭代20231211：显示内容为“经销商名称(经销商编码)”
    //           const name = `${d.name}(${d.code})`;
    //           return (
    //             <Option title={name} key={d.code}>
    //               {name}
    //             </Option>
    //           );
    //         }),
    //     });
    //     // } else {
    //     //   message.error(response.statusMessage);
    //     // }
    //   },
    // });
  }

  // getOrgFilterData = () => {
  //   // 获取经销商（调接口查询真实经销商数据）
  //   let filterData = [];
  //   const orgData = JSON.parse(this.state.originData);
  //   filterData = orgData.map((item) => {
  //     return item.orgCode;
  //   });
  //   this.props.dispatch({
  //     type: 'http/postListList',
  //     payload: { url: '/commodity/vehicle/filter/dealercodes', list: filterData },
  //     callback: (res) => {
  //       if (res.statusCode === '0') {
  //         this.setState({
  //           orgFilterData: res.data,
  //         });
  //       }
  //     },
  //   });
  // };

  dealTreeData = (
    orgParent: any,
    list: {
      map: (arg0: (e: any) => { orgParent: any; sid: any; value: any; label: any }) => {
        (): any;
        new (): any;
        filter: { (arg0: (c: any) => boolean): never[]; new (): any };
      };
    },
  ) => {
    const arr =
      list
        .map((e: { orgParent: any; sid: any; orgCode: any; orgName: any }) => ({
          orgParent: e.orgParent,
          sid: e.sid,
          value: e.orgCode,
          label: e.orgName,
        }))
        .filter((c: { orgParent: any }) => c.orgParent === orgParent) || [];
    arr.forEach((item: { sid: any; children: any }) => {
      const children = this.dealTreeData(item.sid, list);
      if (children.length) {
        item.children = children;
      }
    });
    return arr;
  };
  /**
   * 根据组织id获取经销商数据
   * @param {*} orgId
   */
  fetchDealerData = (orgId: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/getDataWithRes',
      payload: { url: '/mscreditbusiness/merchant/getDealers', orgId },
      callback: (response: { data: any[] }) => {
        // if (response.statusCode === '0') {
        this.setState({
          dealerOptions: response.data
            ?.filter((item: { code: string }) => item.code !== '')
            .map((d: { name: any; code: React.Key | null | undefined }) => {
              const name = `${d.name}(${d.code})`;
              return (
                <Option title={name} key={d.code}>
                  {name}
                </Option>
              );
            }),
        });
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };
  open = () => {
    const fenceId = this.props.location.query.fenceId;
    const { dispatch } = this.props;
    (fenceId
      ? dispatch({
          type: 'electricFenceMng/getData',
          payload: {
            url: '/electricfence/getfencedetail',
            fenceId,
          },
        })
      : Promise.resolve({})
    )
      .catch(() => ({}))
      .then((res: { data: any }) => {
        const record = res.data;
        if (record && record.districtList && record.districtList.length) {
          // 2个种数据结构统一
          Object.assign(record, record.districtList[0]);
        }
        let clist = [];
        let alist = [];
        if (record && record.cityCode && record.cityName) {
          clist.push({
            code: record.cityCode,
            name: record.cityName,
          });
        }
        if (record && record.areaCode && record.areaName) {
          alist.push({
            code: record.areaCode,
            name: record.areaName,
          });
        }
        this.setState(
          {
            record: record,
            isAdd: record ? false : true,
            effectType: record && record.warningBeginDate ? 1 : 0,
            cityList: clist,
            areaList: alist,
          },
          async () => {
            if (record) {
              dispatch({
                type: 'electricFenceMng/getData',
                payload: {
                  url: '/common/area/list',
                  level: 'CITY',
                  parentCode: record.provinceCode,
                },
                callback: (response: any) => {
                  this.setState({ cityList: response.data });
                },
              });
              if (record.cityCode) {
                dispatch({
                  type: 'electricFenceMng/getData',
                  payload: {
                    url: '/common/area/list',
                    level: 'DISTRICT',
                    parentCode: record.cityCode,
                  },
                  callback: (response: any) => {
                    this.setState({ areaList: response.data });
                  },
                });
              }
              this.formRef.current?.setFieldsValue({
                warningConfigs: record.warningConfigs,
                fenceName: record.fenceName,
                fenceUserType: record.fenceUserType,
                dealerCode: record.dealerCode,
                repository: record.repository,
                effectType: record.warningBeginDate && record.warningEndDate ? 1 : 0,
                fenceExpireDate:
                  record.warningBeginDate && record.warningEndDate
                    ? [moment(record.warningBeginDate), moment(record.warningEndDate)]
                    : null,
                provinceCode: record.provinceCode,
                cityCode: record.cityCode ? record.cityCode : null,
                areaCode: record.areaCode ? record.areaCode : null,
              });

              await this.insComplete;
              const code = record.areaCode || record.cityCode || record.provinceCode;
              code && this.setMap(code);
            }
          },
        );
      });
  };

  close = () => {
    this.setState(
      {
        record: null,
        effectType: 0,
        cityList: [],
        areaList: [],
      },
      () => {
        this.formRef.current?.resetFields();
        router.replace(`${self === top ? '' : '/external'}/electricFence/electricFenceMng`);
      },
    );
  };

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (args: any) => {
    const { dispatch } = this.props;
    const fenceId = this.props.location.query.fenceId;
    const { provinceList, cityList, areaList } = this.state;

    const post: any = {
      id: fenceId,
      fenceType: 1,
      fenceUserType: fenceId ? this.state.record.fenceUserType : args.fenceUserType,
      repository: fenceId ? this.state.record.repository : args.repository,
      warningBeginDate: args.fenceExpireDate
        ? args.fenceExpireDate[0].format('YYYY-MM-DD')
        : undefined,
      warningEndDate: args.fenceExpireDate
        ? args.fenceExpireDate[1].format('YYYY-MM-DD')
        : undefined,
      warningConfigs: args.warningConfigs,
      orgCode: fenceId
        ? this.state.record.orgCode
        : args.orgCode && args.orgCode.length
        ? args.orgCode[args.orgCode.length - 1]
        : undefined,
      orgId: fenceId ? this.state.record.orgId : this.state.currentOrgSid,
      dealerCode: fenceId ? this.state.record.dealerCode : args.dealerCode,
      districtList: [],
    };
    let province = provinceList.find((item: any) => item.code == args.provinceCode);
    let dst: any = {
      provinceCode: args.provinceCode,
      provinceName: province ? province.name : null,
    };
    if (args.cityCode) {
      let city = cityList.find((item: any) => item.code == args.cityCode);
      dst.cityCode = args.cityCode;
      dst.cityName = city ? city.name : null;
    }
    if (args.areaCode) {
      let area = areaList.find((item: any) => item.code == args.areaCode);
      dst.areaCode = args.areaCode;
      dst.areaName = area ? area.name : null;
    }
    post.districtList.push(dst);

    dispatch({
      type: 'electricFenceMng/postObj',
      payload: {
        url: !fenceId ? '/electricfence/savefence' : '/electricfence/updateFence',
        ...post,
      },
      callback: (res: any) => {
        message.success('保存成功');
        this.close();
      },
    });
  };

  onEffectTypeChange = (e: any) => {
    this.setState({ effectType: e.target.value });
  };

  setMap = async (code: any) => {
    if (!this.ins) {
      return;
    }
    this.geojson && this.ins.remove(this.geojson);
    if (!code) {
      const province = this.formRef.current.getFieldValue('provinceCode');
      const city = this.formRef.current.getFieldValue('cityCode');
      if (province) {
        code = province;
        if (city) {
          code = city;
        }
      } else {
        return;
      }
    }

    const json = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${code}.json`).then(e => {
      return e.json();
    });

    this.geojson = new AMap.GeoJSON({
      geoJSON: json,
    });
    this.ins.add(this.geojson);
    this.ins.setFitView();
  };

  onProvinceChange = (value: any) => {
    this.setMap(value);
    const { dispatch } = this.props;
    if (value != null) {
      dispatch({
        type: 'electricFenceMng/getData',
        payload: { url: '/common/area/list', level: 'CITY', parentCode: value },
        callback: (response: any) => {
          this.setState({ cityList: response.data, areaList: [] }, () => {
            this.formRef.current?.resetFields(['areaCode', 'cityCode']);
          });
        },
      });
    } else {
      this.setState({ cityList: [], areaList: [] }, () => {
        this.formRef.current?.resetFields(['areaCode', 'cityCode']);
      });
    }
  };

  onCityChange = (value: any) => {
    this.setMap(value);
    const { dispatch } = this.props;
    if (value != null && value != undefined) {
      dispatch({
        type: 'electricFenceMng/getData',
        payload: { url: '/common/area/list', level: 'DISTRICT', parentCode: value },
        callback: (response: any) => {
          this.setState({ areaList: response.data }, () => {
            this.formRef.current?.resetFields(['areaCode']);
          });
        },
      });
    } else {
      this.setState({ areaList: [] }, () => {
        this.formRef.current?.resetFields(['areaCode']);
      });
    }
  };

  onCountyChange = (value: any) => {
    this.setMap(value);
  };

  render() {
    const {
      isAdd,
      effectType,
      provinceList,
      cityList,
      areaList,
      record,
      isDetail,
      dealerOptions,
      fenceUserType,
    } = this.state;
    const { loading } = this.props;
    return (
      <Card
        title={!isDetail ? (isAdd ? '新增围栏' : '编辑围栏') : '围栏详情'}
        onClose={this.close}
        bodyStyle={{ padding: '12px 24px' }}
        width={800}
        extra={
          <Space>
            <Button size="small" onClick={this.close}>
              取消
            </Button>
            {!isDetail ? (
              <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
                保存
              </Button>
            ) : (
              ''
            )}
          </Space>
        }
      >
        <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.onFinish}>
          {this.props.location.query.fenceId ? (
            <>
              <Row>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <Form.Item {...formItemLayout} label="围栏编号">
                    {record && record.fenceCode}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <Form.Item {...formItemLayout} label="围栏名称">
                    {record && record.fenceName}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <Form.Item {...formItemLayout} label="围栏类型">
                    {record && fenceUserTypeHash[record.fenceUserType]}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <Form.Item {...formItemLayout} label="围栏所属组织">
                    {' '}
                    {record && record.orgName}
                  </Form.Item>
                </Col>
              </Row>
              {record?.fenceUserType === '1' && (
                <>
                  <Row>
                    <Col lg={12} md={12} sm={24} xs={24}>
                      <Form.Item {...formItemLayout} label="所属经销商">
                        {record?.dealerName +
                          (record?.dealerCode ? '(' + record?.dealerCode + ')' : '')}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row>
                    <Col lg={12} md={12} sm={24} xs={24}>
                      <Form.Item {...formItemLayout} label="所属仓库">
                        {repositoryHash[record?.repository] || ''}
                      </Form.Item>
                    </Col>
                  </Row>
                </>
              )}
              {/* {record !== null &&
              record.dealerName !== null &&
              record.dealerName !== undefined &&
              record.dealerName.length > 0 ? (
                <Row>
                  <Col lg={12} md={12} sm={24} xs={24}>
                    <Form.Item {...formItemLayout} label="经销商">
                      {record && record.dealerName}
                    </Form.Item>
                  </Col>
                </Row>
              ) : null} */}
            </>
          ) : null}
          <Row>
            {this.props.location.query.fenceId ? null : (
              <>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <FormItem
                    {...formItemLayout}
                    label="围栏类型"
                    name="fenceUserType"
                    rules={[{ required: true, message: '请选择围栏类型' }]}
                  >
                    <Select
                      disabled={isDetail}
                      placeholder="请选择围栏类型"
                      allowClear={false}
                      onChange={e => {
                        this.setState({ fenceUserType: e });
                      }}
                    >
                      <Option key="0">非经销商</Option>
                      <Option key="1">经销商</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col lg={12} md={12} sm={24} xs={24}>
                  <FormItem
                    {...formItemLayout}
                    label="所属组织"
                    name="orgCode"
                    rules={[{ required: true, message: '请选择所属组织' }]}
                  >
                    <Cascader
                      changeOnSelect
                      showSearch
                      options={this.state.orgData}
                      placeholder="请选择所属组织"
                      onChange={e => {
                        this.setState({ currentOrgSid: null, dealerOptions: [] });
                        this.formRef.current?.resetFields(['dealerCode']);
                        if (!e) {
                          return;
                        }

                        const code = e[e.length - 1];
                        let orgData = JSON.parse(this.state.originData);
                        const current = orgData.find((e: any) => e.orgCode === code);
                        this.setState({ currentOrgSid: current.sid });
                        if (current.sid) {
                          this.fetchDealerData(current.sid);
                        }
                        // this.setState({ dealerData: [] });
                        // this.formRef.current?.resetFields(['dealerCode']);
                        // if (!e) {
                        //   return;
                        // }

                        // const code = e[e.length - 1];
                        // let orgData = JSON.parse(this.state.originData);
                        // const current = orgData.find((e) => e.orgCode === code);
                        // // const changeData = orgData.filter(
                        // //   e => e.orgLevelCode.indexOf(current.orgLevelCode + '-') >= 0,
                        // // );
                        // orgData = orgData.filter((e) => e.orgType === 2);
                        // if (!current) {
                        //   return;
                        // }

                        // if (current.orgType === 3) {
                        //   // todo: 如果是授信机构, 是另外的逻辑, 待实现
                        //   return;
                        // }

                        // if (this.state.orgFilterData.indexOf(current.orgCode) > -1) {
                        //   this.setState({
                        //     // dealerData: [
                        //     //   {
                        //     //     label: current.orgName,
                        //     //     value: current.orgCode,
                        //     //     children: this.dealTreeData(
                        //     //       current.sid,
                        //     //       changeData.filter(
                        //     //         e =>
                        //     //           [2].indexOf(e.orgType) > -1 &&
                        //     //           this.state.orgFilterData.indexOf(e.orgCode) > -1,
                        //     //       ),
                        //     //     ),
                        //     //   },
                        //     // ],
                        //     dealerData: this.dealTreeData(
                        //       current.sid,
                        //       orgData.filter(
                        //         (e: any) => this.state.orgFilterData.indexOf(e.orgCode) > -1,
                        //       ),
                        //     ),
                        //   });
                        // } else {
                        //   this.setState({
                        //     // dealerData: this.dealTreeData(
                        //     //   current.sid,
                        //     //   changeData.filter(
                        //     //     e =>
                        //     //       [2].indexOf(e.orgType) > -1 &&
                        //     //       this.state.orgFilterData.indexOf(e.orgCode) > -1,
                        //     //   ),
                        //     // ),
                        //     dealerData: this.dealTreeData(
                        //       current.sid,
                        //       orgData.filter(
                        //         (e: any) => this.state.orgFilterData.indexOf(e.orgCode) > -1,
                        //       ),
                        //     ),
                        //   });
                        // }
                      }}
                    />
                  </FormItem>
                </Col>
                {/* <Col lg={12} md={12} sm={24} xs={24}>
                  <Form.Item {...formItemLayout} label="经销商" name="dealerCode">
                    <Cascader
                      changeOnSelect
                      options={this.state.dealerData}
                      placeholder="请选择经销商"
                    />
                  </Form.Item>
                </Col> */}
                {fenceUserType === '1' || record?.fenceUserType === '1' ? (
                  // 经销商
                  <>
                    <Col lg={12} md={12} sm={24} xs={24}>
                      <Form.Item
                        {...formItemLayout}
                        label="所属经销商"
                        name="dealerCode"
                        rules={[{ required: true, message: '请选择所属经销商' }]}
                      >
                        <Select
                          disabled={isDetail}
                          allowClear={false}
                          placeholder="请选择所属经销商"
                          showSearch
                          getPopupContainer={triggerNode => triggerNode.parentNode}
                          optionFilterProp="children"
                        >
                          {dealerOptions}
                        </Select>
                      </Form.Item>
                    </Col>

                    <Col lg={12} md={12} sm={24} xs={24}>
                      <Form.Item {...formItemLayout} label="所属仓库" name="repository">
                        <Select placeholder="请选择所属仓库" allowClear disabled={isDetail}>
                          <Option key="0">主库</Option>
                          <Option key="1">二库</Option>
                          <Option key="2">二网</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </>
                ) : null}
              </>
            )}

            <Col lg={12} md={12} sm={24} xs={24}>
              <FormItem
                {...formItemLayout}
                label="省级行政区"
                name="provinceCode"
                rules={[{ required: true, message: '请选择省级行政区' }]}
              >
                <Select
                  disabled={isDetail}
                  showSearch
                  allowClear
                  onChange={this.onProvinceChange}
                  placeholder="请选择省级行政区"
                  optionFilterProp="children"
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                >
                  {transferOption(provinceList, ['code', 'name'])}
                </Select>
              </FormItem>
            </Col>
            <Col lg={12} md={12} sm={24} xs={24}>
              <FormItem
                {...formItemLayout}
                label="市级行政区"
                name="cityCode"
                rules={[{ required: false, message: '请选择市级行政区' }]}
              >
                <Select
                  disabled={isDetail}
                  showSearch
                  allowClear
                  onChange={this.onCityChange}
                  placeholder="请选择市级行政区"
                  optionFilterProp="children"
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                >
                  {transferOption(cityList, ['code', 'name'])}
                </Select>
              </FormItem>
            </Col>
            <Col lg={12} md={12} sm={24} xs={24}>
              <FormItem
                {...formItemLayout}
                label="县级行政区"
                name="areaCode"
                rules={[{ required: false, message: '请选择县级行政区' }]}
              >
                <Select
                  disabled={isDetail}
                  showSearch
                  allowClear
                  placeholder="请选择县级行政区"
                  optionFilterProp="children"
                  onChange={this.onCountyChange}
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                >
                  {transferOption(areaList, ['code', 'name'])}
                </Select>
              </FormItem>
            </Col>
            {/* <Col lg={12} md={12} sm={24} xs={24}>
              <Form.Item
                {...formItemLayout}
                label="围栏预警方式"
                name="warningConfigs"
                rules={[{ required: true, message: '请选择围栏预警方式' }]}
              >
                <Checkbox.Group
                  disabled={isDetail}
                  options={[
                    { label: '进入围栏', value: 1 },
                    { label: '离开围栏', value: 2 },
                    { label: '围栏内', value: 3 },
                    { label: '围栏外', value: 4 },
                  ]}
                />
              </Form.Item>
            </Col> */}
            <Col lg={12} md={12} sm={24} xs={24}>
              <FormItem
                {...formItemLayout}
                label="围栏有效期"
                name="effectType"
                rules={[{ required: true, message: '请选择围栏有效期' }]}
                initialValue={0}
              >
                <Radio.Group
                  disabled={isDetail}
                  onChange={this.onEffectTypeChange}
                  options={effectTypeOptions}
                />
              </FormItem>
            </Col>
            {effectType == 1 ? (
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem
                  {...formItemLayout}
                  label="限制日期"
                  name="fenceExpireDate"
                  rules={[{ required: true, message: '请选择限制日期' }]}
                >
                  <DatePicker.RangePicker
                    disabled={isDetail}
                    // placeholder="请选择限制日期"
                    style={{ width: '100%' }}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  />
                </FormItem>
              </Col>
            ) : null}
          </Row>
        </Form>
        <div
          style={{
            height: 485,
            minHeight: 'calc(100vh - 400px)',
            border: '1px solid #d9d9d9',
            position: 'relative',
          }}
        >
          <Map
            ak={'19dbf6ffd63917bac5a923432ed8ca7a'}
            events={{
              created: async (ins: any) => {
                this.ins = ins;
                this.insComplete.resolve(true);
              },
            }}
          />
        </div>
      </Card>
    );
  }
}
export default connect(mapStateToProps)(DistrictAdd);
